package com.ns.scs.user.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.jwt.SystemUtil;
import com.ns.core.utils.rsa.TokenUtil;
import com.ns.core.utils.sg.NbUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.vo.au.SsoUserVO;
import com.ns.core.vo.bs.BaseVO;
import com.ns.core.vo.login.SucObjVO;
import com.ns.scs.user.dto.ScsUserPageDto;
import com.ns.scs.user.entry.ScsUser;
import com.ns.scs.user.mapper.UserMapper;
import com.ns.scs.user.vo.ScsUserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 业务用户实现
 *
 * @author lw
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ScsUserServiceImpl extends ServiceImpl<UserMapper, ScsUser> implements IScsUserService {

    private final UserMapper mapper;


    @Override
    public Page<ScsUserVO> getList(ScsUserPageDto dto) {
        return mapper.getList(dto, new Page<>(dto.getCurrent(), dto.getSize()));
    }

    @Override
    public SucObjVO doLogin(String userAcc, String password) {
        // 1、查询账户
        SsoUserVO user = mapper.getByPhone(userAcc);

        // 2、开始验证
        if (user == null) {
            throw new ResultError("暂无此账户信息");
        }
        // 3、查询密码
        String pwd = mapper.getPwdById(user.getId());
        if (NbUtil.isNull(pwd)) {
            throw new ResultError("此账号尚未设置密码，无法登陆");
        }
        // 4、验证密码
        String inPwd = SystemUtil.getPasswordMd5(user.getId(), password);
        if (!Objects.equals(pwd, inPwd)) {
            throw new ResultError("密码错误");
        }
        // 5、是否禁用
        if (user.getStatus() == 0) {
            throw new ResultError("此账号已被禁用，可申请恢复！");
        }
        // =========== 已登录成功 ============
        // 生成token
        String token = TokenUtil.generateToken(JSON.toJSONString(user));
        // 缓存
        StpUtil.login(user.getId(), token);
        // 组织返回参数
        SucObjVO suc = new SucObjVO();
        suc.setToken(token);
        suc.setU(user);
        return suc;
    }

    @Override
    public long getMaxSort() {
        return mapper.getMaxSort();
    }

    @Override
    public List<BaseVO> getOptions(ScsUserPageDto dto) {
        return mapper.getOptions(dto);
    }
}
